<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 * 生成Dao相关文件
 * 
 * @author  : $Author: spike $
 * @date    : $Date: 2013-12-31 11:49:44 +0800 (二, 2013-12-31) $
 * @version : $Id: build_dao.php 18 2013-12-31 03:49:44Z spike $
 * @rev     : $Revision: 18 $
 */
class Build_dao extends CI_Controller 
{
    private static $_database;
    private static $_host;
    private static $_username;
    private static $_password;

    private static $_dao_path;
    private static $_struct_path;

    public function __construct()
    {
        parent::__construct();

        self::$_database    = 'tcfs';
        self::$_dao_path    = APPPATH.'daos/';
        self::$_struct_path = APPPATH.'daos/structs/';

        $this->config->load('db');
        $cfg = $this->config->item('db_config');
        $db  = $cfg['db_physical'][$cfg['db_single'][self::$_database]]['read'];

        if( empty($db['hostname']) OR 
            empty($db['username']) OR
            empty($db['password'])
        )
        {
            $file = APPPATH.'config/'.ENVIRONMENT.'/db.php';
            show_error("生成 DAO 失败：数据库配置错误，请检查{$file}。");
        }

        self::$_host     = $db['hostname'];
        self::$_username = $db['username'];
        self::$_password = $db['password'];  
    }

    /**
     * [确认信息]
     */
    public function index()
    {
        $db = mysql_connect(self::$_host, self::$_username, self::$_password);
        if (!$db)
        {
            show_error(mysql_error());
        }
        $result = mysql_query("SHOW TABLES FROM ".self::$_database);
        while ($row = mysql_fetch_row($result)) 
        {
            $temp[] = $row[0];
        }
        mysql_free_result($result);

        $data = array(
            'database'    => self::$_database,
            'tables'      => $temp,
            'dao_path'    => self::$_dao_path,
            'struct_path' => self::$_struct_path,
        );
        mysql_close($db);

        $this->load->view('home/header.tpl', $data);
        $this->load->view('build_dao/index.tpl');
        $this->load->view('home/footer.tpl');
    }

    /**
     * [生成Dao和Dao对应的数据结构基类]
     */
    public function build()
    {
        $table = $this->input->post('table');

        if( empty($table)
        )
        {
            show_error("生成 Dao 失败：请选择一张或多张数据表。");
        }

        $db = mysql_connect(self::$_host, self::$_username, self::$_password);
        if (!$db)
        {
            show_error(mysql_error());
        }

        // 指定表 OR 选择所有表
        if($table === '_ALL_TABLES_')
        {
            $result = mysql_query("SHOW TABLES FROM ".self::$_database);
            while ($row = mysql_fetch_row($result)) 
            {
                $tables[] = $row[0];
            }
            mysql_free_result($result);
        }
        else
        {
            $tables[] = $table;
        }

        if( ! $tables OR count($tables)<1)
        {
            show_error("生成 Dao 失败：没有需要生成的表。");
        }

        //获得表结构
        $table_struct = array();
        foreach ($tables as $table_name) 
        {
            mysql_select_db(self::$_database);
            $result = mysql_query("SELECT * FROM {$table_name}");
            if ( ! $result) 
            {
                show_error(mysql_error());
            }

            /* get column metadata */
            $i = 0;
            while ($i < mysql_num_fields($result)) 
            {
                $meta = mysql_fetch_field($result, $i);
                if (!$meta && !$flags) 
                {
                    continue;
                }
                else 
                {
                    $table_struct[$table_name][$i] = $meta;
                }
            
                $i++;

            }
            mysql_free_result($result);
        }
        mysql_close($db);
        
        $daos    = array();
        $structs = array();
        // 生成表结构文件
        foreach ($table_struct as $table_name => $fields)
        {

            $class_name  = ucwords($table_name);
            $dao_name    = "{$class_name}_dao";
            $dao_file    = self::$_dao_path.strtolower($dao_name).'.php';

            $struct_name = "Base_{$class_name}_dao";
            $struct_file = self::$_struct_path.strtolower($struct_name).'.php';

            // 如果不存在Dao文件,新建之
            if( ! file_exists($dao_file))
            {
                $f = fopen($dao_file, FOPEN_WRITE_CREATE_DESTRUCTIVE);
                if( ! $f)
                {
                    show_error("生成 Dao 失败：无法创建[{$dao_file}]。");
                }
                fwrite($f, "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n");
                fwrite($f, "/**\n");
                fwrite($f, " * {$table_name} 表操作方法\n");
                fwrite($f, " * \n");
                fwrite($f, " * @author  : \$Author\$\n");
                fwrite($f, " * @date    : \$Date\$\n");
                fwrite($f, " * @version : \$Id\$\n");
                fwrite($f, " * @rev     : \$Revision\$\n");
                fwrite($f, " * @url     : \$HeadURL\$\n");
                fwrite($f, " */\n\n");
                fwrite($f, "class {$dao_name} extends {$struct_name}\n");
                fwrite($f, "{\n");
                fwrite($f, "    public function __construct()\n");
                fwrite($f, "    {\n");
                fwrite($f, "        parent::__construct();\n");
                fwrite($f, "    }\n");  
                fwrite($f, "}\n");
                fwrite($f, "/* End of file */");  
                fclose($f);
                chmod($dao_file, 0777);
                $daos[] = $dao_file;
            }
            // 写struct文件
            $f = fopen($struct_file, FOPEN_WRITE_CREATE_DESTRUCTIVE);
            if( ! $f)
            {
                show_error("生成 Struct 失败：无法创建[{$struct_file}]。");
            }
            fwrite($f, "<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n");
            fwrite($f, "/**\n");
            fwrite($f, " * {$table_name} 表数据结构\n");
            fwrite($f, " * \n");
            fwrite($f, " * @author  : \$Author\$\n");
            fwrite($f, " * @date    : \$Date\$\n");
            fwrite($f, " * @version : \$Id\$\n");
            fwrite($f, " * @rev     : \$Revision\$\n");
            fwrite($f, " * @url     : \$HeadURL\$\n");            
            fwrite($f, " */\n\n");
            fwrite($f, "class {$struct_name} extends CI_Table_gateway\n");
            fwrite($f, "{\n");
            fwrite($f, "    public function __construct()\n");
            fwrite($f, "    {\n");
            fwrite($f, "        \$this->database = '".self::$_database."';\n");
            fwrite($f, "        \$this->table    = '$table_name';\n");
            fwrite($f, "        \$this->fields   = array(");
            foreach($fields as $field)
            {
                fwrite($f, "'$field->name',");
            }
            fwrite($f, ");\n");
            fwrite($f, "\n");       
            fwrite($f, "        parent::__construct();\n");
            fwrite($f, "    }   \n");   
            fwrite($f, "}\n");
            fwrite($f, "/* End of file */");  
            fclose($f);
            $structs[] = $struct_file;
            chmod($struct_file, 0777);
            unset($class_name, $dao_name, $dao_file, $struct_name, $struct_file);
        }  

        $data = array(
            'daos'    => $daos,
            'structs' => $structs,
        );
        $this->load->view('home/header.tpl', $data);
        $this->load->view('build_dao/result.tpl');
        $this->load->view('home/footer.tpl');
    }
}

/* End of file */